﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Utils.Drawing;
using System.Diagnostics;
using Microsoft.Xna.Framework;

namespace Utils.Drawing
{
    public class AnimTileSprite : Sprite
    {
        Rectangle?[] sourceRects;
        List<Animation> animations = new List<Animation>();
        Animation currentAnim;
        Animation defaultAnim;
        float frame = 0f;

        public AnimTileSprite(Texture2D texture, Animation defaultAnim, Rectangle?[] rects)
            : base(texture)
        {
            this.sourceRects = rects;
            this.currentAnim = this.defaultAnim = defaultAnim;
            AddAnimation(defaultAnim);
        }

        public void AddAnimation(Animation animation)
        {
            Debug.Assert(animation.FirstFrame >= 0 && animation.LastFrame <= sourceRects.Count(), 
                "Animation Frames out of bounds!");
            animations.Add(animation);
        }

        public void SetAnimation(Animation animation)
        {
            currentAnim = animation;
            frame = animation.FirstFrame;
        }

        public override void Draw(float dTime, SpriteRenderer renderer)
        {
            if (currentAnim != null)
            {
                if (!currentAnim.Update(ref frame, dTime))
                {
                    SetAnimation(defaultAnim);
                }
            }

            Debug.Assert(frame >= 0 && frame < sourceRects.Count(), "Illegal Frame idx!");
            source = sourceRects[(int)frame];
            base.Draw(dTime, renderer);
        }
    }
}
